 //
//  NetworkEngine.m
//  Basic
//
//  Created by 裴烨烽 on 16/5/23.
//  Copyright © 2016年 BasicPod. All rights reserved.
//

#import "NetworkEngine.h"
#import "MD5Manager.h"
#import "SBJSON.h"
#import "RequestSerializer.h"


@implementation NetworkEngine


-(instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self){
        self.requestSerializer = [RequestSerializer serializer];
        self.requestSerializer.timeoutInterval = 15;

        self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; // 设置content-Type为text/html
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    }
    return self;
}

-(void)fetchWithPath:(NSString *)path requestParams:(NSDictionary *)requestParams responseObjectClass:(Class)responseObjectClass succeededBlock:(FetchCompletionHandler)block{
    
    
//
//
//    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://192.168.31.61:8080/send_sms_code" parameters:requestParams error:nil];
//   NSURLSessionDataTask *task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        if (!error) {
//            // 现返回的为纯json字符串，需要转两次
//            NSString *jsonStr =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//            NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *respondDic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@"respondObject -- \n %@",respondDic);
//
//        }
//        else
//        {
//
//        }
//    }];
//
//    [task resume];
//    return;
//
//    NSString *url = [NSString stringWithFormat:@"http://192.168.31.61:8080/%@",path];
//    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:requestParams error:nil];
//
//    NSURLSessionDataTask *task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        NSLog(@"123");
//    }];
//    [task resume];
//    return;
//
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:requestParams];

    [tempDic setObject:@"ios" forKey:@"deviceType"];
    
    __weak typeof(self)weakSelf = self;
   [self POST:path parameters:tempDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!weakSelf){
            return ;
        }

        if (responseObject == nil){
            NSError *error = [NSError errorWithDomain:ErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: @"未知错误"}];
            block(NO,nil,error);
        } else {            // 解析成功
            
            dispatch_async(dispatch_get_main_queue(), ^{
                SBJSON *json = [[SBJSON alloc] init];
                
                NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
                NSDictionary *dicWithRequestJson = [json objectWithString:result error:nil];
                //                id responseObjectWithJson = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
#ifdef DEBUG
                NSString *requestURL = [task.currentRequest.URL absoluteString];
                NSLog(@"RESPONSE JSON:%@   \nrequestURL===>%@  \nparams ===== >%@", dicWithRequestJson,requestURL,tempDic );
                
                
                if ([[Tool userDefaultGetWithKey:TestNet_Log] isEqualToString:@"y"]){            // 输出log
                    NSString *str  =  [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                    [[UIAlertView alertViewWithTitle:@"测试log" message:str buttonTitles:@[@"复制Log",@"确定"] callBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                        if (buttonIndex == 0){
                            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                            pasteboard.string = str;
                            [[UIAlertView alertViewWithTitle:@"复制成功" message:nil buttonTitles:@[@"确定"] callBlock:NULL]show];
                        }
                    }]show];
                }
#endif
                
                // 判断是否成功
                // 1. 判断是否有类别
                if (responseObjectClass == nil){        // 没有返回class
                    block(YES,dicWithRequestJson,nil);
                    return;
                }
                // 2. 判断是否是fetchModel 的子类
                if (![responseObjectClass isSubclassOfClass:[FetchModel class]]) {
                    block(YES,dicWithRequestJson,nil);
                    return;
                }
                // 3. 直接返回
                if ([responseObjectClass instancesRespondToSelector:@selector(initWithJSONDict:)]) {
                    block(YES,dicWithRequestJson,nil);
                }
            });
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(self)strongSelf = weakSelf;
        
#ifdef DEBUG
        NSString *requestURL = [task.currentRequest.URL absoluteString];
        NSString *params = [[NSString alloc]initWithData:task.currentRequest.HTTPBody encoding:NSUTF8StringEncoding];
        NSLog(@"FAILURE URL:%@ \nPARAMS:%@ \nAND RESPONSE:%@", requestURL, params, task.response);
#endif
        [strongSelf showResponseCode:task.response WithBlock:^(NSInteger statusCode) {
            block(NO,nil,error);
        }];
    }];
}




#pragma mark - Other Manger
- (void)showResponseCode:(NSURLResponse *)response WithBlock:(void (^)(NSInteger statusCode))block{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger responseStatusCode = [httpResponse statusCode];
    return block(responseStatusCode);
}


-(NSString *)sortModelManagerWithDic:(NSDictionary *)dict{
    NSString *sortString = @"";
    NSArray *keysArray = [dict allKeys];
    NSArray *resultArray = [keysArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    for (NSString *categoryId in resultArray) {
        NSString *keyValueString = [dict objectForKey:categoryId];
        
        NSString *key = categoryId;
        NSString *keyValue = keyValueString;
        sortString = [sortString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,keyValue]];
    }
    sortString = [sortString stringByAppendingString:@"pandaolWR@#!DFS"];
    return sortString;
    
}


-(void)txLogin{

}


- (NSString *)parametersString:(NSDictionary *)parameters {
    NSMutableDictionary *mutableParameters = [parameters mutableCopy];
    //    NSString *apiCode = [mutableParameters objectForKey:@"apiCode"];
    //    [mutableParameters removeObjectForKey:@"apiCode"];
    NSArray *tempKeys = [mutableParameters allKeys];



    NSArray *sortedKeys = [tempKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *key1 = (NSString *)obj1;
        NSString *key2 = (NSString *)obj2;
        return [key1 compare:key2];
    }];

    NSMutableArray *tempArr = [NSMutableArray array];
    //    [tempArr addObject:@"apiCode"];
    [tempArr addObjectsFromArray:sortedKeys];
    //    [mutableParameters setObject:apiCode forKey:@"apiCode"];

    NSString *token = @"";
    for (NSString *key in tempArr) {
        NSString *value = [NSString stringWithFormat:@"%@", parameters[key]];
        token = [token stringByAppendingString:value];
    }
    token = [token stringByAppendingString:@"466ee3b5fb474fc7b5cbf0d9d25c6a85"];
    token = [token md5String];

    [mutableParameters addEntriesFromDictionary:@{@"token": token}];
    return [mutableParameters mmh_JSONString];
}



@end
